
import Util from 'util'

class WeChatService {
    constructor() {
        this.wxSystemInfo = ''
    }

    // 打开调试
    openDebug() {
        wx.setEnableDebug({
            enableDebug: true
        })

    }

    /**
     * API不支持的提醒
     * @throw Exception
     */
    apiNonsupport(apiName) {
        wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        })
        throw new Error('微信版本过低，无法使用' + apiName)
    }
    // 设置授权
    authorize(scope) {
        return new Promise((resolve, reject) => {
            wx.authorize({
                scope: scope,
                success(msg) {
                    resolve(msg)
                },
                fail(msg) {
                    reject(msg)
                }
            })
        })
    }

    // 请求授权
    requestAuthorize(scope) {
        return new Promise((resolve, reject) => {
            wx.getSetting({
                success(res) {
                    if (!res.authSetting[scope]) {
                        wx.authorize({
                            scope: scope,
                            success() {
                                resolve({});
                            },
                            fail() {
                                wx.openSetting()

                                reject({})
                            }
                        })
                    } else {
                        resolve({});
                    }
                },
                fail() {
                    reject({})
                }
            })
        })
    }

    setTitle(titleLabel) {
        wx.setNavigationBarTitle({
            title: titleLabel
        })
    }

    // 获取设备参数
    // @throw Exception
    systemInfo() {
        if (!this.wxSystemInfo) {
            this.wxSystemInfo = wx.getSystemInfoSync()
        }

        return this.wxSystemInfo;
    }

    // 获取微信SDK基础库版本
    // @throw Exception
    getSDKVersion() {
        return this.systemInfo().SDKVersion;
    }


    /**
     * WXML节点信息
     * 基础库 1.4.0 开始支持
     * @throw Exception
     */
    createSelectorQuery() {
        if (wx.createSelectorQuery) {
            return wx.createSelectorQuery()
        } else {
            this.apiNonsupport('wx.createSelectorQuery')
        }
    }

    /**
     * 获取用户的当前设置。
     * 基础库 1.2.0 开始支持
     * @throw Exception
     */
    getSetting(param) {
        if (wx.getSetting) {
            return wx.getSetting(param)
        } else {
            this.apiNonsupport('wx.getSetting')
        }
    }

}

export default WeChatService;